package com.hethongviet.preventing.page;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import com.hethongviet.preventingmachine.R;

import com.hethongviet.preventingmachine.AppMain;
import com.hethongviet.preventingmachine.Config;
import com.hethongviet.preventingmachine.Constants;
import com.hethongviet.preventingmachine.Utils;
import com.hethongviet.preventingmachine.helps.dialog.DialogMessageBack;
import com.hethongviet.preventingmachine.helps.OnSMSMessageFailListener;
import com.hethongviet.preventingmachine.helps.OnSMSMessageListener;
import com.hethongviet.preventingmachine.helps.SMSHelper;
import com.hethongviet.preventingmachine.helps.SmsReceiverDefault;
import com.hethongviet.preventingmachine.helps.TabMenuMultiLine;
import com.hethongviet.preventingmachine.helps.db.AccountSQLite;
import com.hethongviet.preventingmachine.helps.db.CameraSQLite;
import com.hethongviet.preventingmachine.helps.db.DeviceSQLite;
import com.hethongviet.preventingmachine.helps.db.RelaySQLite;
import com.hethongviet.preventingmachine.helps.db.SensorSQLite;
import com.hethongviet.preventingmachine.helps.db.NumberSQLite;
import com.hethongviet.preventingmachine.models.Account;
import com.hethongviet.preventingmachine.models.Camera;
import com.hethongviet.preventingmachine.models.Device;
import com.hethongviet.preventingmachine.models.Number;
import com.hethongviet.preventingmachine.models.Relay;
import com.hethongviet.preventingmachine.models.SMS;
import com.hethongviet.preventingmachine.models.Sensor;
import com.hethongviet.preventingmachine.models.Tab;
import com.hethongviet.preventingmachine.models.Transaction;
import com.hethongviet.preventingmachine.page.PageChangeNameActivity;
import com.hethongviet.preventingmachine.page.PageChangeNumberActivity;
import com.hethongviet.preventingmachine.page.PageChangePasswordActivity;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;

public class PageAdminActivity extends Activity implements
		OnSMSMessageListener, OnSMSMessageFailListener
{
	private final static int TAB_DEVICE = 0;
	private final static int TAB_SENSOR = TAB_DEVICE + 1;
	private final static int TAB_RELAY = TAB_SENSOR + 1;
	private final static int TAB_NUMBERS_ALARM = TAB_RELAY + 1;
	private final static int TAB_NUMBERS_CONTROL = TAB_NUMBERS_ALARM + 1;
	private final static int TAB_CAMERA = TAB_NUMBERS_CONTROL + 1;
	private final static int TOTAL_TABS = TAB_CAMERA + 1;

	private SensorSQLite _SensorSQLite = null;
	private RelaySQLite _RelaySQLite = null;
	private DeviceSQLite _DeviceSQLite = null;
	private AccountSQLite _AccountSQLite = null;
	private NumberSQLite _NumberSQLite = null;
	private CameraSQLite _CameraSQLite = null;

	private Account _Account = null;
	private Device _Device = null;

	private LinearLayout _LayoutListSensors = null;
	private LinearLayout _LayoutListRelays = null;

	private LinearLayout _LayoutTabLine1 = null;
	private LinearLayout _LayoutTabLine2 = null;

	private LinearLayout _LayoutListNumbersAlarm = null;
	private LinearLayout _LayoutListNumbersControl = null;
	private LinearLayout _LayoutListCameras = null;

	private ScrollView _LayoutTabSensor = null;
	private ScrollView _LayoutTabRelay = null;
	private ScrollView _LayoutTabDevice = null;
	private ScrollView _LayoutTabNumbersAlarm = null;
	private ScrollView _LayoutTabNumbersControl = null;
	private ScrollView _LayoutTabCamera = null;

	private Button _ButtonTabSensors = null;
	private Button _ButtonTabRelays = null;
	private Button _ButtonTabDevice = null;
	private Button _ButtonTabNumbersAlarm = null;
	private Button _ButtonTabNumbersControl = null;
	private Button _ButtonTabCamera = null;

	private Button _ButtonUpdateAllSensors = null;
	private Button _ButtonUpdateAllRelays = null;
	private Button _ButtonSaveChangesSensors = null;
	private Button _ButtonSaveChangesRelays = null;
	private Button _ButtonCancelChangesSensors = null;
	private Button _ButtonCancelChangesRelays = null;

	private Button _ButtonNumberAlarmAdd = null;
	private Button _ButtonNumberAlarmSave = null;
	private Button _ButtonNumberAlarmUse = null;
	private Button _ButtonNumberAlarmCancel = null;
	private Button _ButtonNumberControlAdd = null;
	private Button _ButtonNumberControlSave = null;
	private Button _ButtonNumberControlUse = null;
	private Button _ButtonNumberControlCancel = null;

	private EditText _EditTextNumberControl = null;
	private EditText _EditTextNumberAlarm = null;
	private EditText _EditTextCameraName = null;
	private EditText _EditTextCameraAddress = null;

	private Button _ButtonChangePassword = null;
	private Button _ButtonChangeDeviceName = null;
	private Button _ButtonChangeDevicePhoneNumber = null;
	private Button _ButtonCameraAdd = null;
	private Button _ButtonCameraSaveToNumbers = null;

	private ProgressBar _ProgressBarUpdateAllRelays = null;
	private ProgressBar _ProgressBarUpdateAllSensors = null;

	private TextView _TextViewPassword = null;
	private TextView _TextViewDeviceName = null;
	private TextView _TextViewDevicePhoneNumber = null;

	private List<Sensor> _SensorList = null;
	private List<Relay> _RelayList = null;
	private List<Camera> _CameraList = null;

	private List<Number> _NumbersAlarmList = null;
	private List<Number> _NumbersControlList = null;

	private Timer _TimerOutSMS = null;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		Utils.prepareWindow(this);

		setContentView(R.layout.page_admin);

		_LayoutListSensors = (LinearLayout) findViewById(com.hethongviet.preventer.admin.R.id.list_sensors);
		_LayoutListRelays = (LinearLayout) findViewById(com.hethongviet.preventer.admin.R.id.list_relays);

		_LayoutTabLine1 = (LinearLayout) findViewById(com.hethongviet.preventer.admin.R.id.layout_tab_line_1);
		_LayoutTabLine2 = (LinearLayout) findViewById(com.hethongviet.preventer.admin.R.id.layout_tab_line_2);

		_LayoutListNumbersAlarm = (LinearLayout) findViewById(com.hethongviet.preventer.admin.R.id.list_numbers_alarm);
		_LayoutListNumbersControl = (LinearLayout) findViewById(com.hethongviet.preventer.admin.R.id.list_numbers_control);
		_LayoutListCameras = (LinearLayout) findViewById(com.hethongviet.preventer.admin.R.id.list_cameras);

		_LayoutTabRelay = (ScrollView) findViewById(com.hethongviet.preventer.admin.R.id.layout_tab_relays);
		_LayoutTabSensor = (ScrollView) findViewById(com.hethongviet.preventer.admin.R.id.layout_tab_sensors);
		_LayoutTabDevice = (ScrollView) findViewById(com.hethongviet.preventer.admin.R.id.layout_tab_device);
		_LayoutTabNumbersAlarm = (ScrollView) findViewById(com.hethongviet.preventer.admin.R.id.layout_tab_numbers_alarm);
		_LayoutTabNumbersControl = (ScrollView) findViewById(com.hethongviet.preventer.admin.R.id.layout_tab_numbers_control);
		_LayoutTabCamera = (ScrollView) findViewById(com.hethongviet.preventer.admin.R.id.layout_tab_camera);

		_ButtonTabRelays = (Button) findViewById(com.hethongviet.preventer.admin.R.id.button_tab_relays);
		_ButtonTabSensors = (Button) findViewById(com.hethongviet.preventer.admin.R.id.button_tab_sensors);
		_ButtonTabDevice = (Button) findViewById(com.hethongviet.preventer.admin.R.id.button_tab_device);
		_ButtonTabNumbersAlarm = (Button) findViewById(com.hethongviet.preventer.admin.R.id.button_tab_numbers_alarm);
		_ButtonTabNumbersControl = (Button) findViewById(com.hethongviet.preventer.admin.R.id.button_tab_numbers_control);
		_ButtonTabCamera = (Button) findViewById(com.hethongviet.preventer.admin.R.id.button_tab_camera);

		_ButtonNumberAlarmAdd = (Button) findViewById(com.hethongviet.preventer.admin.R.id.button_number_alarm_add);
		_ButtonNumberAlarmSave = (Button) findViewById(com.hethongviet.preventer.admin.R.id.button_number_alarm_save);
		_ButtonNumberAlarmUse = (Button) findViewById(com.hethongviet.preventer.admin.R.id.button_number_alarm_use);
		_ButtonNumberAlarmCancel = (Button) findViewById(com.hethongviet.preventer.admin.R.id.button_number_alarm_cancel);

		_ButtonNumberControlAdd = (Button) findViewById(com.hethongviet.preventer.admin.R.id.button_number_control_add);
		_ButtonNumberControlSave = (Button) findViewById(com.hethongviet.preventer.admin.R.id.button_number_control_save);
		_ButtonNumberControlUse = (Button) findViewById(com.hethongviet.preventer.admin.R.id.button_number_control_use);
		_ButtonNumberControlCancel = (Button) findViewById(com.hethongviet.preventer.admin.R.id.button_number_control_cancel);

		_EditTextNumberAlarm = (EditText) findViewById(com.hethongviet.preventer.admin.R.id.edit_number_alarm);
		_EditTextNumberControl = (EditText) findViewById(com.hethongviet.preventer.admin.R.id.edit_number_control);
		_EditTextCameraAddress = (EditText) findViewById(com.hethongviet.preventer.admin.R.id.edit_camera_address);
		_EditTextCameraName = (EditText) findViewById(com.hethongviet.preventer.admin.R.id.edit_camera_name);

		_ButtonChangeDeviceName = (Button) findViewById(com.hethongviet.preventer.admin.R.id.button_change_device_name);
		_ButtonChangePassword = (Button) findViewById(com.hethongviet.preventer.admin.R.id.button_change_admin_password);
		_ButtonChangeDevicePhoneNumber = (Button) findViewById(com.hethongviet.preventer.admin.R.id.button_change_device_number);

		_ButtonUpdateAllRelays = (Button) findViewById(com.hethongviet.preventer.admin.R.id.button_update_all_relays);
		_ButtonUpdateAllSensors = (Button) findViewById(com.hethongviet.preventer.admin.R.id.button_update_all_sensors);
		_ButtonSaveChangesSensors = (Button) findViewById(com.hethongviet.preventer.admin.R.id.button_sensors_save_change);
		_ButtonSaveChangesRelays = (Button) findViewById(com.hethongviet.preventer.admin.R.id.button_relays_save_change);
		_ButtonCancelChangesSensors = (Button) findViewById(com.hethongviet.preventer.admin.R.id.button_sensors_cancel_change);
		_ButtonCancelChangesRelays = (Button) findViewById(com.hethongviet.preventer.admin.R.id.button_relays_cancel_change);
		_ButtonCameraAdd = (Button) findViewById(com.hethongviet.preventer.admin.R.id.button_camera_add);
		_ButtonCameraSaveToNumbers = (Button) findViewById(com.hethongviet.preventer.admin.R.id.button_camera_save_to_numbers);

		_ProgressBarUpdateAllRelays = (ProgressBar) findViewById(com.hethongviet.preventer.admin.R.id.progress_bar_update_all_relays);
		_ProgressBarUpdateAllSensors = (ProgressBar) findViewById(com.hethongviet.preventer.admin.R.id.progress_bar_update_all_sensors);

		_TextViewDeviceName = (TextView) findViewById(com.hethongviet.preventer.admin.R.id.device_name);
		_TextViewDevicePhoneNumber = (TextView) findViewById(com.hethongviet.preventer.admin.R.id.device_number);
		_TextViewPassword = (TextView) findViewById(com.hethongviet.preventer.admin.R.id.admin_password);

		initTab();
		initDB();

		try
		{
			_Account = _AccountSQLite.getAll().get(0);
			_Device = _DeviceSQLite.getAll().get(0);
			_SensorList = _SensorSQLite.getAll();
			_RelayList = _RelaySQLite.getAll();
			_CameraList = _CameraSQLite.getAll();
		} catch (Exception e)
		{
			e.printStackTrace();
			finish();
			return;
		}

		if (_Device == null || _Account == null || _SensorList == null
				|| _RelayList == null || _RelayList.size() == 0
				|| _SensorList.size() == 0)
		{
			Utils.debug("ERROR! Error data!!!");
			finish();
			return;
		}

		SMSHelper.setPassword(_Account.getPassword());
		SMSHelper.setDeviceNumber(_Device.getNumber());

		List<Number> numbersAll = _NumberSQLite.getAll();

		if (_NumbersAlarmList == null)
			_NumbersAlarmList = new ArrayList<Number>();

		if (_NumbersControlList == null)
			_NumbersControlList = new ArrayList<Number>();

		if (numbersAll != null && numbersAll.size() > 0)
		{
			for (Number number : numbersAll)
			{
				if (number.isAlarm())
				{
					_NumbersAlarmList.add(number);
				}

				if (number.isControl())
				{
					_NumbersControlList.add(number);
				}
			}
		}

		showListSensors(_Device.getMaxSensors(), _SensorList);
		showListRelays(_Device.getMaxRelays(), _RelayList);

		showListNumbersAlarm();
		showListNumbersControl();
		showListCameras();

		prepareForDeviceChange();

		prepareForAddNumberAlarm();

		prepareForAddNumberControl();

		prepareForAddCamera();
	}

	@Override
	protected void onResume()
	{

		SmsReceiverDefault.setOnSMSMessageListener(this);
		SMSHelper.setActivity(this);
		SMSHelper.setMessageId(0);

		super.onResume();
	}

	private void prepareForAddCamera()
	{
		_ButtonCameraSaveToNumbers.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0)
			{
				if (_NumbersAlarmList == null || _NumbersAlarmList.size() == 0
						|| _NumbersControlList == null
						|| _NumbersControlList.size() == 0)
				{
					showDialogWithCatch(R.string.message_error_have_no_number);
					return;
				}

				if (_NumbersAlarmList != null && _NumbersAlarmList.size() != 0)
				{
					for (Number number : _NumbersAlarmList)
					{
						SMSHelper.sendCamera(number.getNumber(), _CameraList);
					}
				}
				if (_NumbersControlList != null
						&& _NumbersControlList.size() != 0)
				{
					for (Number number : _NumbersControlList)
					{
						SMSHelper.sendCamera(number.getNumber(), _CameraList);
					}
				}
			}
		});

		_ButtonCameraAdd.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0)
			{
				String name = _EditTextCameraName.getText().toString();
				if (Utils.isStringNull(name))
				{
					showDialogWithCatch(R.string.message_error_input_null_name);
					return;
				}

				for (int index = 0; index < name.length(); index++)
				{
					char c = name.charAt(index);

					if (!Character.isLetterOrDigit(c) && c != '_' && c != '-'
							&& c != ' ')
					{
						showDialogWithCatch(R.string.message_error_wrong_input_name);
						return;
					}
				}

				if (name.length() < Constants.LENGTH_MIN_NAME)
				{
					showDialogWithCatch(R.string.message_error_input_too_short_name);
					return;
				}

				if (name.length() > Constants.LENGTH_MAX_NAME)
				{
					showDialogWithCatch(R.string.message_error_input_too_long_name);
					return;
				}

				String address = _EditTextCameraAddress.getText().toString();
				if (Utils.isStringNull(address))
				{
					showDialogWithCatch(R.string.message_error_input_null_address);
					return;
				}

				if (address.length() < Constants.LENGTH_MIN_ADDRESS)
				{
					showDialogWithCatch(R.string.message_error_input_too_short_address);
					return;
				}

				if (address.length() > Constants.LENGTH_MAX_ADDRESS)
				{
					showDialogWithCatch(R.string.message_error_input_too_long_address);
					return;
				}

				for (int index = 0; index < address.length(); index++)
				{
					char c = address.charAt(index);

					if (!Utils.isValidWebAddressChar(c))
					{
						showDialogWithCatch(R.string.message_error_wrong_input_name);
						return;
					}
				}

				Camera camera = new Camera();
				camera.setAddress(address);
				camera.setName(name);

				_CameraSQLite.insert(camera);
				_CameraList = _CameraSQLite.getAll();

				showListCameras();

				_EditTextCameraAddress.setText("");
				_EditTextCameraName.setText("");
			}
		});
	}

	private void prepareForDeviceChange()
	{
		_TextViewDeviceName.setText(_Device.getName());
		_TextViewDevicePhoneNumber.setText(_Device.getNumber());
		_TextViewPassword.setText(_Account.getPassword());

		_ButtonChangeDeviceName.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0)
			{
				Intent intent = new Intent(PageAdminActivity.this,
						PageChangeNameActivity.class);
				intent.putExtra(Constants.EXTRA_NAME, _Device.getName());
				intent.putExtra(Constants.EXTRA_REQUEST, Constants.REQUEST_CHANGE_DEVICE_NAME);
				startActivityForResult(intent, Constants.REQUEST_CHANGE_DEVICE_NAME);
			}
		});

		_ButtonChangeDevicePhoneNumber.setVisibility(View.INVISIBLE);
		_ButtonChangeDevicePhoneNumber.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0)
			{
				Intent intent = new Intent(PageAdminActivity.this,
						PageChangeNumberActivity.class);
				intent.putExtra(Constants.EXTRA_NUMBER, _Device.getNumber());
				intent.putExtra(Constants.EXTRA_REQUEST, Constants.REQUEST_CHANGE_DEVICE_PHONE_NUMBER);
				startActivityForResult(intent, Constants.REQUEST_CHANGE_DEVICE_PHONE_NUMBER);
			}
		});

		_ButtonChangePassword.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0)
			{
				Intent intent = new Intent(PageAdminActivity.this,
						PageChangePasswordActivity.class);
				intent.putExtra(Constants.EXTRA_PASSWORD, _Account.getPassword());
				intent.putExtra(Constants.EXTRA_REQUEST, Constants.REQUEST_CHANGE_PASSWORD);
				startActivityForResult(intent, Constants.REQUEST_CHANGE_PASSWORD);
			}
		});
	}

	private void prepareForAddNumberAlarm()
	{
		if (_NumbersAlarmList == null
				|| _NumbersAlarmList.size() <= Constants.MAX_PHONE_ALARM)
		{
			_ButtonNumberAlarmAdd.setVisibility(View.VISIBLE);
		}
		else
			_ButtonNumberAlarmAdd.setVisibility(View.GONE);

		showAddingNumberAlarmGUI(false);

		_ButtonNumberAlarmAdd.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0)
			{
				showAddingNumberAlarmGUI(true);
				_ButtonNumberAlarmAdd.setVisibility(View.GONE);
			}
		});

		_ButtonNumberAlarmUse.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v)
			{
				String _newNumber = _EditTextNumberAlarm.getText().toString();
				if (_newNumber == null || _newNumber.equals(""))
				{
					_EditTextNumberAlarm.setText("");
					showDialogWithCatch(R.string.message_error_input_null);
					return;
				}

				for (int index = 0; index < _newNumber.length(); index++)
				{
					char c = _newNumber.charAt(index);

					if (!Character.isDigit(c) && c != '+')
					{
						showDialogWithCatch(R.string.message_error_wrong_input_number);
						return;
					}
				}

				if (_NumbersAlarmList != null)
				{
					for (Number number : _NumbersAlarmList)
					{
						if (number.getNumber().equals(_newNumber))
						{
							showDialogWithCatch(R.string.message_error_input_number_already);
							return;
						}
					}
				}
				else
					_NumbersAlarmList = new ArrayList<Number>();

				final Number number = new Number();
				number.setNumber(_newNumber);
				number.setAlarm(true);
				number.setActive(false);

				_NumberSQLite.insert(number);

				List<Number> numbersAll = _NumberSQLite.getAll();

				_NumbersAlarmList = new ArrayList<Number>();

				for (Number numberAvailable : numbersAll)
				{
					if (numberAvailable.isControl())
					{
						_NumbersAlarmList.add(numberAvailable);
					}
				}

				if (_NumbersAlarmList.size() <= Constants.MAX_PHONE_ALARM)
				{
					_ButtonNumberAlarmAdd.setVisibility(View.VISIBLE);
				}
				else
					_ButtonNumberAlarmAdd.setVisibility(View.GONE);

				/* Add to GUI */
				final ViewHolderNumber holder = new ViewHolderNumber(
						PageAdminActivity.this, number, _NumbersAlarmList,
						_LayoutListNumbersAlarm);

				holder.addView(SMSHelper.CODE_SYNCHRONIZE_NUMBERS_ALARM, SMSHelper.DEBUG_SMS_SYNCHRONIZE_NUMBERS_ALARM_USER, R.string.message_fail_synchronize_numbers_alarm, _SensorList, _ButtonNumberAlarmSave);

				/* Hide adding GUI */
				showAddingNumberAlarmGUI(false);

				_ButtonNumberAlarmAdd.setVisibility(View.VISIBLE);
				_ButtonNumberAlarmSave.setVisibility(View.VISIBLE);
				_EditTextNumberAlarm.setText("");

			}
		});
		_ButtonNumberAlarmCancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v)
			{
				/* Hide adding GUI */
				showAddingNumberAlarmGUI(false);

				_ButtonNumberAlarmAdd.setVisibility(View.VISIBLE);
				_EditTextNumberAlarm.setText("");
			}
		});
		_ButtonNumberAlarmSave.setVisibility(View.GONE);
		_ButtonNumberAlarmSave.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v)
			{
				/* Hide adding GUI */
				showAddingNumberAlarmGUI(false);

				_ButtonNumberAlarmAdd.setVisibility(View.VISIBLE);

				/* Send SMS */
				Utils.showProgress(PageAdminActivity.this);
				SMSHelper.setupAdmin(_NumbersAlarmList, SMSHelper.CODE_SETUP_PHONE_ALARM, R.string.message_fail_add_numbers_alarm);

				debugSendSMS(SMSHelper.DEBUG_SMS_SETUP_NUMBERS_ALARM);
			}
		});

	}

	private void showAddingNumberAlarmGUI(boolean isShow)
	{
		if (isShow)
		{
			_EditTextNumberAlarm.setVisibility(View.VISIBLE);

			_ButtonNumberAlarmUse.setVisibility(View.VISIBLE);
			_ButtonNumberAlarmCancel.setVisibility(View.VISIBLE);

		}
		else
		{
			_EditTextNumberAlarm.setVisibility(View.GONE);

			_ButtonNumberAlarmUse.setVisibility(View.GONE);
			_ButtonNumberAlarmCancel.setVisibility(View.GONE);
		}
	}

	private void showAddingNumberControlGUI(boolean isShow)
	{
		if (isShow)
		{
			_EditTextNumberControl.setVisibility(View.VISIBLE);

			_ButtonNumberControlUse.setVisibility(View.VISIBLE);
			_ButtonNumberControlCancel.setVisibility(View.VISIBLE);

		}
		else
		{
			_EditTextNumberControl.setVisibility(View.GONE);

			_ButtonNumberControlUse.setVisibility(View.GONE);
			_ButtonNumberControlCancel.setVisibility(View.GONE);
		}
	}

	private void prepareForAddNumberControl()
	{

		if (_NumbersControlList == null
				|| _NumbersControlList.size() <= Constants.MAX_PHONE_CONTROL)
		{
			_ButtonNumberControlAdd.setVisibility(View.VISIBLE);
		}
		else
			_ButtonNumberControlAdd.setVisibility(View.GONE);

		showAddingNumberControlGUI(false);

		_ButtonNumberControlAdd.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0)
			{
				showAddingNumberControlGUI(true);
				_ButtonNumberControlAdd.setVisibility(View.GONE);
			}
		});

		_ButtonNumberControlUse.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v)
			{
				String _newNumber = _EditTextNumberControl.getText().toString();
				if (_newNumber == null || _newNumber.equals(""))
				{
					showDialogWithCatch(R.string.message_error_input_null);
					return;
				}

				if (_newNumber.length() < Constants.LENGTH_MIN_NUMBER)
				{
					showDialogWithCatch(R.string.message_error_input_too_short_number);
					return;
				}

				if (_newNumber.length() > Constants.LENGTH_MAX_NUMBER)
				{
					showDialogWithCatch(R.string.message_error_input_too_long_number);
					return;
				}

				for (int index = 0; index < _newNumber.length(); index++)
				{
					char c = _newNumber.charAt(index);

					if (!Character.isDigit(c) && c != '+')
					{
						showDialogWithCatch(R.string.message_error_wrong_input_number);
						return;
					}
				}

				if (_NumbersControlList != null)
				{
					for (Number number : _NumbersControlList)
					{
						if (number.getNumber().equals(_newNumber))
						{
							showDialogWithCatch(R.string.message_error_input_number_already);
							return;
						}
					}
				}
				else
				{
					_NumbersControlList = new ArrayList<Number>();
				}

				final Number number = new Number();
				number.setNumber(_newNumber);
				number.setControl(true);
				number.setActive(false);

				_NumberSQLite.insert(number);

				List<Number> numbersAll = _NumberSQLite.getAll();

				_NumbersControlList = new ArrayList<Number>();

				for (Number numberAvailable : numbersAll)
				{
					if (numberAvailable.isControl())
					{
						_NumbersControlList.add(numberAvailable);
					}
				}

				if (_NumbersControlList.size() <= Constants.MAX_PHONE_ALARM)
				{
					_ButtonNumberControlAdd.setVisibility(View.VISIBLE);
				}
				else
					_ButtonNumberControlAdd.setVisibility(View.GONE);

				/* Add to GUI */
				final ViewHolderNumber holder = new ViewHolderNumber(
						PageAdminActivity.this, number, _NumbersControlList,
						_LayoutListNumbersControl);

				holder.addView(SMSHelper.CODE_SYNCHRONIZE_NUMBERS_CONTROL, SMSHelper.DEBUG_SMS_SYNCHRONIZE_NUMBERS_CONTROL_USER, R.string.message_fail_synchronize_numbers_control, _RelayList, _ButtonNumberControlSave);

				/* Hide adding GUI */
				showAddingNumberControlGUI(false);

				_ButtonNumberControlAdd.setVisibility(View.VISIBLE);
				_ButtonNumberControlSave.setVisibility(View.VISIBLE);
				_EditTextNumberControl.setText("");

			}
		});
		_ButtonNumberControlCancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v)
			{
				/* Hide adding GUI */
				showAddingNumberControlGUI(false);

				_ButtonNumberControlAdd.setVisibility(View.VISIBLE);
				_EditTextNumberControl.setText("");
			}
		});
		_ButtonNumberControlSave.setVisibility(View.GONE);
		_ButtonNumberControlSave.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v)
			{
				/* Hide adding GUI */
				showAddingNumberControlGUI(false);

				_ButtonNumberControlAdd.setVisibility(View.VISIBLE);

				/* Send SMS */
				Utils.showProgress(PageAdminActivity.this);
				SMSHelper.setupAdmin(_NumbersControlList, SMSHelper.CODE_SETUP_PHONE_CONTROL, R.string.message_fail_add_numbers_control);

				debugSendSMS(SMSHelper.DEBUG_SMS_SETUP_NUMBERS_CONTROL);
			}
		});

	}

	private void initDB()
	{
		_SensorSQLite = new SensorSQLite(this,
				AppMain.getInstance().getDBName());
		_RelaySQLite = new RelaySQLite(this, AppMain.getInstance().getDBName());
		_AccountSQLite = new AccountSQLite(this,
				AppMain.getInstance().getDBName());
		_DeviceSQLite = new DeviceSQLite(this,
				AppMain.getInstance().getDBName());
		_NumberSQLite = new NumberSQLite(this,
				AppMain.getInstance().getDBName());
		_CameraSQLite = new CameraSQLite(this,
				AppMain.getInstance().getDBName());
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		if (resultCode == RESULT_OK)
		{
			switch (requestCode)
			{
				case Constants.REQUEST_CHANGE_DEVICE_NAME:
					_Device = _DeviceSQLite.getAll().get(0);
					_TextViewDeviceName.setText(_Device.getName());
					break;

				case Constants.REQUEST_CHANGE_CAMERA:
					if (data != null)
					{
						long idDB = data.getLongExtra(Constants.EXTRA_IDDB, -1);
						if (idDB >= 0)
						{
							Camera camera = new Camera();
							camera.setIdDB(idDB);

							camera.setName(data.getStringExtra(Constants.EXTRA_NAME));
							camera.setAddress(data.getStringExtra(Constants.EXTRA_ADDRESS));

							_CameraSQLite.insert(camera);
							_CameraList = _CameraSQLite.getAll();

							showListCameras();
						}
					}

					break;

				case Constants.REQUEST_CHANGE_DEVICE_PHONE_NUMBER:
					if (data != null)
					{
						String number = data.getStringExtra(Constants.EXTRA_NUMBER);
						if (number != null)
						{
							_Device.setNumber(number);
							_DeviceSQLite.insert(_Device);
							_TextViewDevicePhoneNumber.setText(_Device.getNumber());

							SMSHelper.setDeviceNumber(_Device.getNumber());

						}
					}
					break;
				case Constants.REQUEST_CHANGE_NAME_SENSOR:
					if (data != null)
					{
						String nameSensor = data.getStringExtra(Constants.EXTRA_NAME);
						if (nameSensor != null)
						{
							_SensorList.get(_IndexSensorChanged).setName(nameSensor);
							View view = _LayoutListSensors.getChildAt(_IndexSensorChanged);
							Button button = (Button) view.findViewById(R.id.layout_one_sensor_button);
							button.setText(nameSensor);
							_IndexSensorChanged = -1;

							if (_ButtonSaveChangesSensors.getVisibility() != View.VISIBLE)
							{
								_ButtonSaveChangesSensors.setVisibility(View.VISIBLE);
								_ButtonCancelChangesSensors.setVisibility(View.VISIBLE);
							}
							if (_ButtonUpdateAllSensors.isClickable())
							{
								/* Disable buttons */
								_ButtonUpdateAllSensors.setClickable(false);
								_ButtonUpdateAllSensors.setTextColor(Color.GRAY);
							}
						}
					}
					break;
				case Constants.REQUEST_CHANGE_NAME_RELAY:
					if (data != null)
					{
						String nameRelay = data.getStringExtra(Constants.EXTRA_NAME);
						if (nameRelay != null)
						{
							_RelayList.get(_IndexRelayChanged).setName(nameRelay);
							View view = _LayoutListRelays.getChildAt(_IndexRelayChanged);
							Button button = (Button) view.findViewById(R.id.layout_one_relay_button);
							button.setText(nameRelay);
							_IndexRelayChanged = -1;

							if (_ButtonSaveChangesRelays.getVisibility() != View.VISIBLE)
							{
								_ButtonSaveChangesRelays.setVisibility(View.VISIBLE);
								_ButtonCancelChangesRelays.setVisibility(View.VISIBLE);
							}

							if (_ButtonUpdateAllRelays.isClickable())
							{
								/* Disable buttons */
								_ButtonUpdateAllRelays.setClickable(false);
								_ButtonUpdateAllRelays.setTextColor(Color.GRAY);
							}
						}
					}
					break;
				case Constants.REQUEST_CHANGE_PASSWORD:
					_Account = _AccountSQLite.getAll().get(0);
					_TextViewPassword.setText(_Account.getPassword());
					break;
			}
		}
	}

	@Override
	protected Dialog onCreateDialog(int id)
	{
		if (id == R.string.message_success_change_name_relays
				|| id == R.string.message_success_change_name_sensors
				|| id == R.string.message_success_add_numbers_control
				|| id == R.string.message_success_add_numbers_alarm
				|| id == R.string.message_success_change_name
				|| id == R.string.message_success_change_password
				|| id == R.string.message_success_change_username
				|| id == R.string.message_success_change_number)
		{
			return new DialogMessageBack(this, false, id, false);
		}
		else if (id == R.string.message_error_input_too_long_number)
		{
			return new DialogMessageBack(this, true,
					String.format(getString(id), Constants.LENGTH_MAX_NUMBER),
					false);
		}
		else if (id == R.string.message_error_input_too_short_number)
		{
			return new DialogMessageBack(this, true,
					String.format(getString(id), Constants.LENGTH_MIN_NUMBER),
					false);
		}
		else if (id == R.string.message_error_input_too_long_name)
		{
			return new DialogMessageBack(this, true,
					String.format(getString(id), Constants.LENGTH_MAX_NAME),
					false);
		}
		else if (id == R.string.message_error_input_too_short_name)
		{
			return new DialogMessageBack(this, true,
					String.format(getString(id), Constants.LENGTH_MIN_NAME),
					false);
		}
		else if (id == R.string.message_error_input_too_long_address)
		{
			return new DialogMessageBack(this, true,
					String.format(getString(id), Constants.LENGTH_MAX_ADDRESS),
					false);
		}
		else if (id == R.string.message_error_input_too_short_address)
		{
			return new DialogMessageBack(this, true,
					String.format(getString(id), Constants.LENGTH_MIN_ADDRESS),
					false);
		}
		else
			return new DialogMessageBack(this, true, id, false);
	}

	private void initTab()
	{
		/* Process for tab menu */
		Tab[] tabs = new Tab[TOTAL_TABS];
		List<View> listLines = new ArrayList<View>();

		tabs[TAB_DEVICE] = new Tab();
		tabs[TAB_DEVICE].setButton(_ButtonTabDevice);
		tabs[TAB_DEVICE].setViewContain(_LayoutTabDevice);

		tabs[TAB_SENSOR] = new Tab();
		tabs[TAB_SENSOR].setButton(_ButtonTabSensors);
		tabs[TAB_SENSOR].setViewContain(_LayoutTabSensor);

		tabs[TAB_RELAY] = new Tab();
		tabs[TAB_RELAY].setButton(_ButtonTabRelays);
		tabs[TAB_RELAY].setViewContain(_LayoutTabRelay);
		listLines.add(_LayoutTabLine1);

		tabs[TAB_NUMBERS_ALARM] = new Tab();
		tabs[TAB_NUMBERS_ALARM].setButton(_ButtonTabNumbersAlarm);
		tabs[TAB_NUMBERS_ALARM].setViewContain(_LayoutTabNumbersAlarm);

		tabs[TAB_NUMBERS_CONTROL] = new Tab();
		tabs[TAB_NUMBERS_CONTROL].setButton(_ButtonTabNumbersControl);
		tabs[TAB_NUMBERS_CONTROL].setViewContain(_LayoutTabNumbersControl);

		tabs[TAB_CAMERA] = new Tab();
		tabs[TAB_CAMERA].setButton(_ButtonTabCamera);
		tabs[TAB_CAMERA].setViewContain(_LayoutTabCamera);
		listLines.add(_LayoutTabLine2);

		new TabMenuMultiLine(tabs, R.drawable.button_tab2,
				R.drawable.button_tab2_highlight, listLines);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(com.hethongviet.preventer.admin.R.menu.page_admin, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		if (item.getItemId() == com.hethongviet.preventer.admin.R.id.menu_update_all)
		{
			_CountUpdateMessage = 4;
			Utils.showProgress(PageAdminActivity.this);
			_TimerOutSMS = new Timer();
			TimerTask task = new TimerTask() {

				@Override
				public void run()
				{
					Utils.hideProgressDialog();
					onSMSMessageFail(null, R.string.message_fail_update_all);
				}
			};

			_TimerOutSMS.schedule(task, Constants.TIME_OUT_SMS);

			SMSHelper.updateAll();

			debugSendSMS(SMSHelper.DEBUG_SMS_UPDATE_ALL_1);
			debugSendSMS(SMSHelper.DEBUG_SMS_UPDATE_ALL_2);
			debugSendSMS(SMSHelper.DEBUG_SMS_UPDATE_ALL_3);
			debugSendSMS(SMSHelper.DEBUG_SMS_UPDATE_ALL_4);
		}
		return true;
	}

	private int _CountUpdateMessage = 0;

	@Override
	public void onSMSMessageIncoming(SMS sms)
	{
		String message = Utils.prepareMessage(sms.getMessage());

		Utils.debug("Message receive = " + message);

		if (Utils.isStringNull(message))
		{
			Utils.debug("ERROR----- wrong message! NULL");
			return;
		}

		if (_CountUpdateMessage != 0)
		/* Update all: receive 4 SMS messages */
		{
			if (message.length() <= SMSHelper.CODE_UPDATE_ALL.length() + 1)
			{
				Utils.debug("ERROR----- wrong message!");
				return;
			}

			String codeSMS = message.substring(0, SMSHelper.CODE_UPDATE_ALL.length() + 1);
			Utils.debug("codeSMS = " + codeSMS);

			if (!codeSMS.equals(SMSHelper.CODE_RESPONSE_UPDATE_ALL_PHONE_ALARM)
					&& !codeSMS.equals(SMSHelper.CODE_RESPONSE_UPDATE_ALL_PHONE_CONTROL)
					&& !codeSMS.equals(SMSHelper.CODE_RESPONSE_UPDATE_ALL_RELAY)
					&& !codeSMS.equals(SMSHelper.CODE_RESPONSE_UPDATE_ALL_SENSOR))
			{
				Utils.debug("ERROR----- wrong message!");
				return;
			}

			String insideMessage = null;
			try
			{
				insideMessage = message.substring(SMSHelper.CODE_UPDATE_ALL.length() + 2, message.length() - 8);
			} catch (Exception e)
			{
				e.printStackTrace();
				return;
			}

			if (Utils.isStringNull(insideMessage))
			{
				Utils.debug("ERROR----- wrong message!Null content");
				return;
			}

			Utils.debug("insideMessage = " + insideMessage);

			if (codeSMS.equals(SMSHelper.CODE_RESPONSE_UPDATE_ALL_PHONE_ALARM))
			{
				_CountUpdateMessage--;

				String[] numbers = insideMessage.split("[)(]+");

				if (numbers == null || numbers.length == 0)
				{
					Utils.debug("ERROR----- no alarm number!");
					return;
				}
				Utils.debug("Names size = " + numbers.length);

				List<Number> numbersList = _NumberSQLite.getAll();

				for (int indexName = 0; indexName < numbers.length; indexName++)
				{
					String numberString = numbers[indexName];
					if (numberString == null
							|| numberString.equals("")
							|| numberString.charAt(0) == SMSHelper.CODE_REPLACE_NULL)
					{
						continue;
					}

					boolean isAdded = false;

					if (numbersList != null)
					{
						for (Number number : numbersList)
						{
							if (number.getNumber().equals(numberString)
									&& number.isAlarm())
							{
								isAdded = true;
								break;
							}
						}
					}

					if (!isAdded)
					{
						Number numberInsert = new Number();
						numberInsert.setNumber(numberString);
						numberInsert.setAlarm(true);
						numberInsert.setActive(true);

						_NumberSQLite.insert(numberInsert);
					}
				}
			}
			else if (codeSMS.equals(SMSHelper.CODE_RESPONSE_UPDATE_ALL_PHONE_CONTROL))
			{
				_CountUpdateMessage--;

				String[] numbers = insideMessage.split("[)(]+");

				if (numbers == null || numbers.length == 0)
				{
					Utils.debug("ERROR----- no alarm number!");
					return;
				}
				Utils.debug("Names size = " + numbers.length);

				List<Number> numbersList = _NumberSQLite.getAll();

				for (int indexName = 0; indexName < numbers.length; indexName++)
				{
					String numberString = numbers[indexName];
					if (numberString == null
							|| numberString.equals("")
							|| numberString.charAt(0) == SMSHelper.CODE_REPLACE_NULL)
					{
						continue;
					}

					boolean isAdded = false;

					if (numbersList != null)
					{
						for (Number number : numbersList)
						{
							if (number.getNumber().equals(numberString)
									&& number.isControl())
							{
								isAdded = true;
								break;
							}
						}
					}

					if (!isAdded)
					{
						Number numberInsert = new Number();
						numberInsert.setNumber(numberString);
						numberInsert.setControl(true);
						numberInsert.setActive(true);

						_NumberSQLite.insert(numberInsert);
					}
				}
			}

			else if (codeSMS.equals(SMSHelper.CODE_RESPONSE_UPDATE_ALL_RELAY))
			{
				_CountUpdateMessage--;

				Utils.debug("Update all relays!!!");

				final int INDEX_RELAY_NAMES = 0;
				final int INDEX_RELAY_STATUS = INDEX_RELAY_NAMES + 1;
				final int INDEX_DEVICE_NAME = INDEX_RELAY_STATUS + 1;
				@SuppressWarnings("unused")
				final int INDEX_DEVICE_TEMPERATURE = INDEX_DEVICE_NAME + 1;

				String[] strings = insideMessage.split("[-]");

				if (strings == null || strings.length == 0)
				{
					Utils.debug("ERROR----- no thing!");
					return;
				}

				String status = null;
				try
				{
					status = strings[INDEX_RELAY_STATUS].substring(0, strings[INDEX_RELAY_STATUS].length() - 1);
				} catch (Exception e)
				{
					e.printStackTrace();
					status = null;
				}
				if (Utils.isStringNull(status))
				{
					Utils.debug("ERROR----- null status");
					return;
				}

				Utils.debug("status = " + status);

				String deviceName = null;

				try
				{
					deviceName = strings[INDEX_DEVICE_NAME].substring(1, strings[INDEX_DEVICE_NAME].length() - 1);
				} catch (Exception e)
				{
					e.printStackTrace();
					deviceName = null;
				}
				if (Utils.isStringNull(deviceName))
				{
					Utils.debug("ERROR----- null device name");
					return;
				}

				_Device.setName(deviceName);
				_DeviceSQLite.insert(_Device);

				List<Relay> relayList = _RelaySQLite.getAll();

				/* Names */
				String relayNames = null;
				try
				{
					relayNames = strings[INDEX_RELAY_NAMES].substring(0, strings[INDEX_RELAY_NAMES].length() - 1);
				} catch (Exception e)
				{
					e.printStackTrace();
					relayList = null;
				}
				if (Utils.isStringNull(relayNames))
				{
					Utils.debug("ERROR----- null relay name");
					return;
				}

				String[] names = relayNames.split("[)(]+");

				if (names == null || names.length == 0)
				{
					Utils.debug("ERROR----- no relay!");
					return;
				}

				Utils.debug("Names size = " + names.length);
				for (int indexName = 0; indexName < names.length; indexName++)
				{
					String name = names[indexName];
					if (name != null && !name.equals("")
							&& name.charAt(0) != SMSHelper.CODE_REPLACE_NULL)
					{
						relayList.get(indexName).setName(names[indexName]);
					}

					char c = status.charAt(indexName);
					if (c == '0')
					{
						relayList.get(indexName).setOn(false);
					}
					else
					{
						relayList.get(indexName).setOn(true);
					}

					_RelaySQLite.insert(relayList.get(indexName));

				}
			}

			else if (codeSMS.equals(SMSHelper.CODE_RESPONSE_UPDATE_ALL_SENSOR))
			{
				_CountUpdateMessage--;

				Utils.debug("Update all sensor!!");

				String[] names = insideMessage.split("[)(]+");

				if (names == null || names.length == 0)
				{
					Utils.debug("ERROR----- no sensor!");
					return;
				}

				Utils.debug("Names size = " + names.length);

				List<Sensor> sensorList = _SensorSQLite.getAll();

				for (int indexName = 0; indexName < names.length; indexName++)
				{
					String name = names[indexName];
					if (name != null && !name.equals("")
							&& name.charAt(0) != SMSHelper.CODE_REPLACE_NULL)
					{
						sensorList.get(indexName).setName(names[indexName]);

						_SensorSQLite.insert(sensorList.get(indexName));
					}
				}
			}

			if (_CountUpdateMessage == 0)
			{
				Utils.hideProgressDialog();
			}
		}
		else
		{
			Transaction transaction = SMSHelper.solve(message);
			if (transaction != null)
			{
				String codeSMS = transaction.getCodeSend();
				Utils.debug("codeSMS = " + codeSMS);

				if (Utils.isStringNull(codeSMS))
				{
					Utils.debug("ERROR----- wrong message! null code");
					return;
				}

				String contentSMS = transaction.getMessageReceive();
				Utils.debug("contentSMS = " + contentSMS);

				if (Utils.isStringNull(contentSMS))
				{
					Utils.debug("ERROR----- wrong content! null content");
					return;
				}

				if (codeSMS.equals(SMSHelper.CODE_UPDATE_RELAY))
				{
					Utils.debug("Update all relays!!!");

					String insideMessage = null;
					try
					{
						insideMessage = contentSMS.substring(1, contentSMS.length() - 3);
					} catch (Exception e)
					{
						e.printStackTrace();
						return;
					}

					if (Utils.isStringNull(insideMessage))
					{
						Utils.debug("ERROR----- wrong content! null content22");
						return;
					}

					Utils.debug("insideMessage = " + insideMessage);

					final int INDEX_RELAY_NAMES = 0;
					final int INDEX_RELAY_STATUS = INDEX_RELAY_NAMES + 1;
					final int INDEX_DEVICE_NAME = INDEX_RELAY_STATUS + 1;
					@SuppressWarnings("unused")
					final int INDEX_DEVICE_TEMPERATURE = INDEX_DEVICE_NAME + 1;

					String[] strings = insideMessage.split("[-]");

					if (strings == null || strings.length == 0)
					{
						Utils.debug("ERROR----- no thing!");
						return;
					}
					String status = null;
					try
					{
						status = strings[INDEX_RELAY_STATUS].substring(1, strings[INDEX_RELAY_STATUS].length() - 1);
					} catch (Exception e)
					{
						e.printStackTrace();
						status = null;
					}

					if (Utils.isStringNull(status))
					{
						Utils.debug("ERROR----- null status");
						return;
					}

					Utils.debug("status = " + status);

					/* Names */
					String relayNames = null;
					try
					{
						relayNames = strings[INDEX_RELAY_NAMES].substring(1, strings[INDEX_RELAY_NAMES].length() - 1);
					} catch (Exception e)
					{
						e.printStackTrace();
						relayNames = null;
					}

					if (Utils.isStringNull(relayNames))
					{
						Utils.debug("ERROR----- null relay name");
						return;
					}

					String[] names = relayNames.split("[)(]+");

					if (names != null && names.length > 0)
					{

						Utils.debug("Names size = " + names.length);

						for (int indexName = 0; indexName < names.length; indexName++)
						{
							_RelayList.get(indexName).setName(names[indexName]);

							char c = status.charAt(indexName);
							if (c == '0')
							{
								_RelayList.get(indexName).setOn(false);
							}
							else
							{
								_RelayList.get(indexName).setOn(true);
							}

							_RelaySQLite.insert(_RelayList.get(indexName));

							/* Update UI */
							View view = _LayoutListRelays.getChildAt(indexName);
							if (view != null)
							{
								Button button = (Button) view.findViewById(R.id.layout_one_relay_button);
								if (button != null)
								{
									button.setText(names[indexName]);

									button.setBackgroundDrawable(getResources().getDrawable(c == '0' ? R.drawable.button_off
											: R.drawable.button_on));
								}

							}
						}
					}
					else
					{
						Utils.debug("ERROR----- no relay!");
					}

					for (int indexView = 0; indexView < _LayoutListRelays.getChildCount(); indexView++)
					{
						View view = _LayoutListRelays.getChildAt(indexView);
						Button buttonRename = (Button) view.findViewById(com.hethongviet.preventer.admin.R.id.layout_one_relay_button_rename);

						buttonRename.setClickable(true);
						buttonRename.setTextColor(Color.BLACK);
					}

					_ProgressBarUpdateAllRelays.setVisibility(View.GONE);
					_ButtonUpdateAllRelays.setClickable(true);
					_ButtonUpdateAllRelays.setTextColor(Color.BLACK);
				}
				else if (codeSMS.equals(SMSHelper.CODE_UPDATE_SENSOR))
				{
					Utils.debug("update sensor!!!!");

					String insideMessage = null;
					try
					{
						insideMessage = contentSMS.substring(2, contentSMS.length() - 4);
					} catch (Exception e)
					{
						e.printStackTrace();
						insideMessage = null;
					}
					if (Utils.isStringNull(insideMessage))
					{
						Utils.debug("ERROR----- null insideMessage");
						return;
					}

					Utils.debug("insideMessage = " + insideMessage);

					String[] names = insideMessage.split("[)(]+");

					if (names != null && names.length > 0)
					{

						Utils.debug("Names size = " + names.length);

						for (int indexName = 0; indexName < names.length; indexName++)
						{
							/* Update db */
							_SensorList.get(indexName).setName(names[indexName]);
							_SensorSQLite.insert(_SensorList.get(indexName));

							/* Update UI */
							View view = _LayoutListSensors.getChildAt(indexName);
							if (view != null)
							{
								Button button = (Button) view.findViewById(R.id.layout_one_sensor_button);
								if (button != null)
									button.setText(names[indexName]);
							}
						}
					}
					else
					{
						Utils.debug("ERROR----- no sensor!");
					}

					for (int indexView = 0; indexView < _LayoutListSensors.getChildCount(); indexView++)
					{
						View view = _LayoutListSensors.getChildAt(indexView);
						Button buttonRename = (Button) view.findViewById(com.hethongviet.preventer.admin.R.id.layout_one_sensor_button_rename);

						buttonRename.setClickable(true);
						buttonRename.setTextColor(Color.BLACK);
					}

					_ProgressBarUpdateAllSensors.setVisibility(View.GONE);
					_ButtonUpdateAllSensors.setClickable(true);
					_ButtonUpdateAllSensors.setTextColor(Color.BLACK);
				}
				else if (codeSMS.equals(SMSHelper.CODE_CONTROL_DEVICE))
				{
					String insideMessage = null;
					try
					{
						insideMessage = contentSMS.substring(1, contentSMS.length() - 1);

					} catch (Exception e)
					{
						e.printStackTrace();
						insideMessage = null;
					}
					if (Utils.isStringNull(insideMessage))
					{
						Utils.debug("ERROR----- null insideMessage");
						return;
					}
					Utils.debug("status = " + insideMessage);

					for (int indexStatus = 0; indexStatus < insideMessage.length(); indexStatus++)
					{
						char c = insideMessage.charAt(indexStatus);
						if (c == 'b')
						{
							continue;
						}

						boolean isOn = (c == '1');
						_RelayList.get(indexStatus).setOn(isOn);
						_RelaySQLite.insert(_RelayList.get(indexStatus));

						/* Update UI */
						View view = _LayoutListRelays.getChildAt(indexStatus);
						if (view != null)
						{
							ProgressBar progressBar = (ProgressBar) view.findViewById(R.id.layout_one_relay_progress_bar);

							if (progressBar != null
									&& progressBar.getVisibility() == View.VISIBLE)
							{
								progressBar.setVisibility(View.GONE);

								Button button = (Button) view.findViewById(R.id.layout_one_relay_button);
								if (button != null)
								{
									button.setBackgroundDrawable(getResources().getDrawable(isOn ? R.drawable.button_on
											: R.drawable.button_off));
								}
							}

							Button buttonRename = (Button) view.findViewById(com.hethongviet.preventer.admin.R.id.layout_one_relay_button_rename);
							if (buttonRename != null)
							{
								buttonRename.setTextColor(Color.BLACK);
								buttonRename.setClickable(true);
							}
						}
						break;
					}

				}
				else if (codeSMS.equals(SMSHelper.CODE_RENAME_RELAY))
				{
					if (contentSMS.contains(SMSHelper.CODE_OK))
					{
						for (Relay relay : _RelayList)
						{
							_RelaySQLite.insert(relay);
						}

						showDialogWithCatch(R.string.message_success_change_name_relays);

						/* Enable buttons */
						_ButtonUpdateAllRelays.setClickable(true);
						_ButtonUpdateAllRelays.setTextColor(Color.BLACK);

						_ButtonSaveChangesRelays.setVisibility(View.GONE);
						_ButtonCancelChangesRelays.setVisibility(View.GONE);
					}
					else
					{
						showDialogWithCatch(R.string.message_fail_change_name_relays);
					}

					Utils.hideProgressDialog();
				}
				else if (codeSMS.equals(SMSHelper.CODE_RENAME_SENSOR))
				{
					if (contentSMS.contains(SMSHelper.CODE_OK))
					{
						for (Sensor sensor : _SensorList)
						{
							_SensorSQLite.insert(sensor);
						}
						showDialogWithCatch(R.string.message_success_change_name_sensors);

						/* Enable buttons */
						_ButtonUpdateAllSensors.setClickable(true);
						_ButtonUpdateAllSensors.setTextColor(Color.BLACK);

						_ButtonSaveChangesSensors.setVisibility(View.GONE);
						_ButtonCancelChangesSensors.setVisibility(View.GONE);
					}
					else
					{
						showDialogWithCatch(R.string.message_fail_change_name_sensors);
					}

					Utils.hideProgressDialog();
				}
				else if (codeSMS.equals(SMSHelper.CODE_SETUP_PHONE_ALARM))
				{
					Utils.hideProgressDialog();
					if (contentSMS.contains(SMSHelper.CODE_OK))
					{

						for (Number number : _NumbersAlarmList)
						{
							number.setActive(true);
							_NumberSQLite.insert(number);
						}

						showDialogWithCatch(R.string.message_success_add_numbers_alarm);

						_ButtonNumberAlarmSave.setVisibility(View.GONE);
					}
					else
					{
						showDialogWithCatch(R.string.message_fail_add_numbers_alarm);
					}

				}
				else if (codeSMS.equals(SMSHelper.CODE_SETUP_PHONE_CONTROL))
				{

					Utils.hideProgressDialog();

					if (contentSMS.contains(SMSHelper.CODE_OK))
					{

						for (Number number : _NumbersControlList)
						{
							number.setActive(true);
							_NumberSQLite.insert(number);
						}

						showDialogWithCatch(R.string.message_success_add_numbers_control);

						_ButtonNumberControlSave.setVisibility(View.GONE);
					}
					else
					{
						showDialogWithCatch(R.string.message_fail_add_numbers_control);
					}

				}

				else if (codeSMS.equals(SMSHelper.CODE_SYNCHRONIZE_NUMBERS_ALARM))
				{

					for (int index = 0; index < _NumbersAlarmList.size(); index++)
					{
						final Number number = _NumbersAlarmList.get(index);

						if (transaction.getRecipient().equals(number.getNumber()))
						{
							/* Update UI */
							View view = _LayoutListNumbersAlarm.getChildAt(index);
							if (view != null)
							{
								ProgressBar progressBar = (ProgressBar) view.findViewById(R.id.layout_one_number_progress_bar);

								if (progressBar != null
										&& progressBar.getVisibility() == View.VISIBLE)
								{
									progressBar.setVisibility(View.GONE);
								}

								Button buttonDelete = (Button) view.findViewById(R.id.layout_one_number_button_delete);
								Button buttonSynchronize = (Button) view.findViewById(R.id.layout_one_number_button_synchronize);
								if (buttonDelete != null)
								{
									buttonDelete.setClickable(true);
									buttonDelete.setTextColor(Color.BLACK);
								}
								if (buttonSynchronize != null)
								{
									buttonSynchronize.setClickable(true);
									buttonSynchronize.setTextColor(Color.BLACK);
								}

								ImageView imageViewSynchronize = (ImageView) view.findViewById(R.id.layout_one_number_image_synchronize);
								if (imageViewSynchronize != null)
								{
									imageViewSynchronize.setImageResource(contentSMS.contains(SMSHelper.CODE_OK) ? R.drawable.synchronize_ok
											: R.drawable.synchronize_error);
									imageViewSynchronize.setVisibility(View.VISIBLE);
								}
							}

							if (contentSMS.contains(SMSHelper.CODE_OK))
							{
								number.setStatusSynchronize(Number.SYNCHRONIZE_OK);
								_NumberSQLite.insert(number);
							}
							else
							{
								number.setStatusSynchronize(Number.SYNCHRONIZE_ERROR);
								_NumberSQLite.insert(number);
							}

							return;
						}
					}

				}

				else if (codeSMS.equals(SMSHelper.CODE_SYNCHRONIZE_NUMBERS_CONTROL))
				{

					for (int index = 0; index < _NumbersControlList.size(); index++)
					{
						final Number number = _NumbersControlList.get(index);

						if (transaction.getRecipient().equals(number.getNumber()))
						{
							/* Update UI */
							View view = _LayoutListNumbersControl.getChildAt(index);
							if (view != null)
							{
								ProgressBar progressBar = (ProgressBar) view.findViewById(R.id.layout_one_number_progress_bar);

								if (progressBar != null
										&& progressBar.getVisibility() == View.VISIBLE)
								{
									progressBar.setVisibility(View.GONE);
								}

								Button buttonDelete = (Button) view.findViewById(R.id.layout_one_number_button_delete);
								Button buttonSynchronize = (Button) view.findViewById(R.id.layout_one_number_button_synchronize);
								if (buttonDelete != null)
								{
									buttonDelete.setClickable(true);
									buttonDelete.setTextColor(Color.BLACK);
								}
								if (buttonSynchronize != null)
								{
									buttonSynchronize.setClickable(true);
									buttonSynchronize.setTextColor(Color.BLACK);
								}

								ImageView imageViewSynchronize = (ImageView) view.findViewById(R.id.layout_one_number_image_synchronize);
								if (imageViewSynchronize != null)
								{
									imageViewSynchronize.setImageResource(contentSMS.contains(SMSHelper.CODE_OK) ? R.drawable.synchronize_ok
											: R.drawable.synchronize_error);
									imageViewSynchronize.setVisibility(View.VISIBLE);
								}
							}

							if (contentSMS.contains(SMSHelper.CODE_OK))
							{
								number.setStatusSynchronize(Number.SYNCHRONIZE_OK);
								_NumberSQLite.insert(number);
							}
							else
							{
								number.setStatusSynchronize(Number.SYNCHRONIZE_ERROR);
								_NumberSQLite.insert(number);
							}

							return;
						}
					}

				}

			}
		}

	}

	private void showDialogWithCatch(int id)
	{
		try
		{
			showDialog(id);
		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	private void showListCameras()
	{
		if (_CameraList == null || _CameraList.size() == 0)
		{
			_ButtonCameraSaveToNumbers.setVisibility(View.GONE);
			return;
		}

		_ButtonCameraSaveToNumbers.setVisibility(View.VISIBLE);

		int total = _CameraList.size();

		_LayoutListCameras.removeAllViews();

		final LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		for (int index = 0; index < total; index++)
		{
			final View view = layoutInflater.inflate(R.layout.layout_one_camera, null);

			final Camera camera = _CameraList.get(index);

			final ViewHolderCamera holder = new ViewHolderCamera();

			holder.textViewAddress = (TextView) view.findViewById(R.id.layout_one_camera_address);
			holder.textViewName = (TextView) view.findViewById(R.id.layout_one_camera_name);
			holder.buttonDelete = (Button) view.findViewById(R.id.layout_one_camera_button_delete);
			holder.buttonModify = (Button) view.findViewById(R.id.layout_one_camera_button_edit);

			holder.buttonDelete.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0)
				{
					_CameraList.remove(camera);
					_LayoutListCameras.removeView(view);
					_CameraSQLite.delete(camera);
				}
			});

			holder.buttonModify.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0)
				{
					Intent intent = new Intent(PageAdminActivity.this,
							PageChangeCameraActivity.class);
					intent.putExtra(Constants.EXTRA_ADDRESS, camera.getAddress());
					intent.putExtra(Constants.EXTRA_NAME, camera.getName());
					intent.putExtra(Constants.EXTRA_IDDB, camera.getIdDB());
					startActivityForResult(intent, Constants.REQUEST_CHANGE_CAMERA);
				}
			});

			holder.textViewAddress.setText(camera.getAddress());
			holder.textViewName.setText(camera.getName());

			_LayoutListCameras.addView(view);
		}

	}

	private void showListNumbersAlarm()
	{

		_LayoutListNumbersAlarm.removeAllViews();

		if (_NumbersAlarmList == null || _NumbersAlarmList.size() == 0)
			return;

		int total = _NumbersAlarmList.size();

		for (int index = 0; index < total; index++)
		{
			final Number number = _NumbersAlarmList.get(index);

			final ViewHolderNumber holder = new ViewHolderNumber(this, number,
					_NumbersAlarmList, _LayoutListNumbersAlarm);

			holder.addView(SMSHelper.CODE_SYNCHRONIZE_NUMBERS_ALARM, SMSHelper.DEBUG_SMS_SYNCHRONIZE_NUMBERS_ALARM_USER, R.string.message_fail_synchronize_numbers_alarm, _SensorList, _ButtonNumberAlarmSave);

			if (_ButtonNumberAlarmSave.getVisibility() == View.GONE
					&& !number.isActive())
			{
				_ButtonNumberAlarmSave.setVisibility(View.VISIBLE);
			}
		}

	}

	private void showListNumbersControl()
	{
		_LayoutListNumbersControl.removeAllViews();
		if (_NumbersControlList == null || _NumbersControlList.size() == 0)
			return;

		int total = _NumbersControlList.size();

		for (int index = 0; index < total; index++)
		{
			final Number number = _NumbersControlList.get(index);

			final ViewHolderNumber holder = new ViewHolderNumber(this, number,
					_NumbersControlList, _LayoutListNumbersControl);

			holder.addView(SMSHelper.CODE_SYNCHRONIZE_NUMBERS_CONTROL, SMSHelper.DEBUG_SMS_SYNCHRONIZE_NUMBERS_CONTROL_USER, R.string.message_fail_synchronize_numbers_control, _RelayList, _ButtonNumberControlSave);
			if (_ButtonNumberControlSave.getVisibility() == View.GONE
					&& !number.isActive())
			{
				_ButtonNumberControlSave.setVisibility(View.VISIBLE);
			}
		}

	}

	private int _IndexSensorChanged = -1;
	private int _IndexRelayChanged = -1;

	private void showListSensors(int maxSensors, final List<Sensor> sensors)
	{
		int sensorLength = (sensors != null) ? sensors.size() : 0;
		int totalReal = (maxSensors > sensorLength) ? sensorLength : maxSensors;

		if (totalReal != 0)
		{
			_LayoutListSensors.removeAllViews();

			final LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

			for (int index = 0; index < totalReal; index++)
			{
				final View view = layoutInflater.inflate(R.layout.layout_one_sensor, null);

				final ViewHolderSensor holder = new ViewHolderSensor();
				holder.button = (Button) view.findViewById(R.id.layout_one_sensor_button);
				holder.buttonRename = (Button) view.findViewById(com.hethongviet.preventer.admin.R.id.layout_one_sensor_button_rename);
				holder.textView = (TextView) view.findViewById(R.id.layout_one_sensor_index);

				final Sensor sensor = sensors.get(index);

				holder.button.setText(sensor.getName());
				holder.textView.setText((index + 1) + "");

				_LayoutListSensors.addView(view);
				final int indexTemp = index;

				holder.buttonRename.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0)
					{
						_IndexSensorChanged = indexTemp;

						Intent intent = new Intent(PageAdminActivity.this,
								PageChangeNameActivity.class);
						intent.putExtra(Constants.EXTRA_NAME, sensor.getName());
						intent.putExtra(Constants.EXTRA_REQUEST, Constants.REQUEST_CHANGE_NAME_SENSOR);
						startActivityForResult(intent, Constants.REQUEST_CHANGE_NAME_SENSOR);
					}
				});
			}
		}

		_ButtonUpdateAllSensors.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0)
			{
				/* Send SMS update all */
				SMSHelper.updateElement(SMSHelper.CODE_UPDATE_SENSOR, R.string.message_fail_update_sensors);
				debugSendSMS(SMSHelper.DEBUG_SMS_UPDATE_SENSORS);

				/* Wait */
				_ProgressBarUpdateAllSensors.setVisibility(View.VISIBLE);

				/* Disable buttons */
				_ButtonUpdateAllSensors.setClickable(false);
				_ButtonUpdateAllSensors.setTextColor(Color.GRAY);
				_ButtonSaveChangesSensors.setClickable(false);
				_ButtonSaveChangesSensors.setTextColor(Color.GRAY);

				for (int indexView = 0; indexView < _LayoutListSensors.getChildCount(); indexView++)
				{
					View view = _LayoutListSensors.getChildAt(indexView);
					Button buttonRename = (Button) view.findViewById(com.hethongviet.preventer.admin.R.id.layout_one_sensor_button_rename);

					buttonRename.setClickable(false);
					buttonRename.setTextColor(Color.GRAY);
				}
			}
		});
		_ButtonCancelChangesSensors.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0)
			{
				/* Disable buttons */
				_ButtonUpdateAllSensors.setClickable(true);
				_ButtonUpdateAllSensors.setTextColor(Color.BLACK);

				_SensorList = _SensorSQLite.getAll();

				for (int indexView = 0; indexView < _LayoutListSensors.getChildCount(); indexView++)
				{
					View view = _LayoutListSensors.getChildAt(indexView);
					Button button = (Button) view.findViewById(R.id.layout_one_sensor_button);

					button.setText(_SensorList.get(indexView).getName());
				}
				_ButtonSaveChangesSensors.setVisibility(View.GONE);
				_ButtonCancelChangesSensors.setVisibility(View.GONE);
			}
		});
		_ButtonSaveChangesSensors.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0)
			{
				Utils.showProgress(PageAdminActivity.this);

				SMSHelper.renameSensors(_SensorList, R.string.message_fail_change_name_sensors);
				debugSendSMS(SMSHelper.DEBUG_SMS_RENAME_SENSORS);
			}
		});
	}

	private void showListRelays(int maxRelays, final List<Relay> relays)
	{
		int relayLength = (relays != null) ? relays.size() : 0;
		final int totalReal = (maxRelays > relayLength) ? relayLength
				: maxRelays;

		if (totalReal != 0)
		{
			_LayoutListRelays.removeAllViews();

			final LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

			for (int index = 0; index < totalReal; index++)
			{
				final View view = layoutInflater.inflate(R.layout.layout_one_relay, null);

				final ViewHolderRelay holder = new ViewHolderRelay();
				holder.progressBar = (ProgressBar) view.findViewById(R.id.layout_one_relay_progress_bar);
				holder.button = (Button) view.findViewById(R.id.layout_one_relay_button);
				holder.buttonRename = (Button) view.findViewById(com.hethongviet.preventer.admin.R.id.layout_one_relay_button_rename);

				final Relay relay = relays.get(index);

				holder.button.setText(relay.getName());
				holder.button.setBackgroundDrawable(getResources().getDrawable(relay.isOn() ? R.drawable.button_on
						: R.drawable.button_off));
				holder.progressBar.setVisibility(View.GONE);
				holder.textView = (TextView) view.findViewById(R.id.layout_one_relay_index);

				final int indexRelay = index;

				holder.button.setEnabled(false);
				holder.textView.setText((index + 1) + "");

				holder.buttonRename.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0)
					{
						_IndexRelayChanged = indexRelay;

						Intent intent = new Intent(PageAdminActivity.this,
								PageChangeNameActivity.class);
						intent.putExtra(Constants.EXTRA_NAME, relay.getName());
						intent.putExtra(Constants.EXTRA_REQUEST, Constants.REQUEST_CHANGE_NAME_RELAY);
						startActivityForResult(intent, Constants.REQUEST_CHANGE_NAME_RELAY);
					}
				});
				holder.button.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v)
					{
						/* SMS turn relay */
						SMSHelper.controlRelay(totalReal, indexRelay, !relay.isOn(), R.string.message_fail_control_relay, view);
						debugSendSMS(SMSHelper.DEBUG_SMS_CONTROL_DEVICE);

						/* Wait */
						holder.progressBar.setVisibility(View.VISIBLE);

						/* Disable button */
						holder.button.setClickable(false);
						holder.buttonRename.setClickable(false);
						holder.buttonRename.setTextColor(Color.GRAY);
					}
				});

				_LayoutListRelays.addView(view);
			}

		}

		_ButtonUpdateAllRelays.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0)
			{
				/* Send SMS update all */
				SMSHelper.updateElement(SMSHelper.CODE_UPDATE_RELAY, R.string.message_fail_update_relays);
				debugSendSMS(SMSHelper.DEBUG_SMS_UPDATE_RELAYS);

				/* Wait */
				_ProgressBarUpdateAllRelays.setVisibility(View.VISIBLE);

				/* Disable buttons */
				_ButtonUpdateAllRelays.setClickable(false);
				_ButtonUpdateAllRelays.setTextColor(Color.GRAY);

				for (int indexView = 0; indexView < _LayoutListRelays.getChildCount(); indexView++)
				{
					View view = _LayoutListRelays.getChildAt(indexView);
					Button buttonRename = (Button) view.findViewById(com.hethongviet.preventer.admin.R.id.layout_one_relay_button_rename);

					buttonRename.setClickable(false);
					buttonRename.setTextColor(Color.GRAY);
				}
			}
		});
		_ButtonSaveChangesRelays.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0)
			{
				Utils.showProgress(PageAdminActivity.this);

				SMSHelper.renameRelays(_RelayList, R.string.message_fail_change_name_relays);
				debugSendSMS(SMSHelper.DEBUG_SMS_RENAME_RELAYS);
			}
		});
		_ButtonCancelChangesRelays.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0)
			{
				/* Disable buttons */
				_ButtonUpdateAllRelays.setClickable(true);
				_ButtonUpdateAllRelays.setTextColor(Color.BLACK);

				_RelayList = _RelaySQLite.getAll();

				for (int indexView = 0; indexView < _LayoutListRelays.getChildCount(); indexView++)
				{
					View view = _LayoutListRelays.getChildAt(indexView);
					Button button = (Button) view.findViewById(R.id.layout_one_relay_button);

					button.setText(_RelayList.get(indexView).getName());
				}
				_ButtonSaveChangesRelays.setVisibility(View.GONE);
				_ButtonCancelChangesRelays.setVisibility(View.GONE);
			}
		});
	}

	private static class ViewHolderSensor
	{
		Button button = null;
		Button buttonRename = null;
		TextView textView = null;
	}

	private static class ViewHolderCamera
	{
		TextView textViewName = null;
		TextView textViewAddress = null;
		Button buttonDelete = null;
		Button buttonModify = null;
	}

	private static class ViewHolderRelay
	{
		ProgressBar progressBar = null;
		Button button = null;
		Button buttonRename = null;
		TextView textView = null;
	}

	private class ViewHolderNumber
	{
		Activity activity = null;
		Number number = null;
		List<Number> numbersList = null;
		LinearLayout layoutListNumbers = null;

		Button buttonDelete = null;
		Button buttonSynchronize = null;
		ImageView imageViewSynchronize = null;
		ImageView imageViewNew = null;
		TextView textNumber = null;
		ProgressBar progressBar = null;

		ViewHolderNumber(Activity activity, Number number,
				List<Number> numbersList, LinearLayout layoutListNumbers)
		{
			this.activity = activity;
			this.number = number;
			this.numbersList = numbersList;
			this.layoutListNumbers = layoutListNumbers;
		}

		void addView(final String codeSMS, final String codeSMSDebug,
				final int messageFailId, final Object object,
				final Button buttonNumberSave)
		{
			final LayoutInflater layoutInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			final View view = layoutInflater.inflate(R.layout.layout_one_number, null);

			buttonDelete = (Button) view.findViewById(R.id.layout_one_number_button_delete);
			textNumber = (TextView) view.findViewById(R.id.layout_one_number);

			textNumber.setText(number.getNumber());
			imageViewSynchronize = (ImageView) view.findViewById(R.id.layout_one_number_image_synchronize);
			imageViewNew = (ImageView) view.findViewById(R.id.layout_one_number_image_new);
			buttonSynchronize = (Button) view.findViewById(R.id.layout_one_number_button_synchronize);
			progressBar = (ProgressBar) view.findViewById(R.id.layout_one_number_progress_bar);

			if (!number.isActive())
				imageViewNew.setVisibility(View.VISIBLE);

			imageViewSynchronize.setImageResource(number.getStatusSynchronize() == Number.SYNCHRONIZE_OK ? R.drawable.synchronize_ok
					: R.drawable.synchronize_error);

			if (number.getStatusSynchronize() == Number.SYNCHRONIZE_NOT_YET)
				imageViewSynchronize.setVisibility(View.GONE);
			else
				imageViewSynchronize.setVisibility(View.VISIBLE);

			buttonSynchronize.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0)
				{
					progressBar.setVisibility(View.VISIBLE);
					imageViewSynchronize.setVisibility(View.GONE);

					buttonDelete.setClickable(false);
					buttonDelete.setTextColor(Color.GRAY);

					buttonSynchronize.setClickable(false);
					buttonSynchronize.setTextColor(Color.GRAY);

					SMSHelper.synchronize(codeSMS, number.getNumber(), _Device.getName(), object, messageFailId, _CameraList);

					debugSendSMS(codeSMSDebug);
				}
			});

			buttonDelete.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0)
				{
					numbersList.remove(number);

					layoutListNumbers.removeView(view);

					numbersList.remove(number);

					NumberSQLite numberSQLite = new NumberSQLite(activity,
							AppMain.getInstance().getDBName());
					numberSQLite.delete(number);

					buttonNumberSave.setVisibility(View.VISIBLE);
				}
			});
			layoutListNumbers.addView(view);
		}
	}

	private void debugSendSMS(final String message)
	{

		final SMS sms = new SMS();
		sms.setRecipient(SMSHelper.getDeviceNumber());
		sms.setMessage(message);

		if (Config.IS_DEBUG_SMS_RECEIVE)
		{
			new Thread(new Runnable() {

				@Override
				public void run()
				{
					try
					{
						Thread.sleep(Constants.TIME_DEBUG_SEND_SMS);
					} catch (Exception e)
					{
						e.printStackTrace();
					}
					PageAdminActivity.this.runOnUiThread(new Runnable() {

						@Override
						public void run()
						{
							onSMSMessageIncoming(sms);
						}
					});
				}
			}).start();

		}
	}

	@Override
	public void onSMSMessageFail(final Transaction transaction,
			final int messageFailId)
	{
		runOnUiThread(new Runnable() {

			@Override
			public void run()
			{
				if (messageFailId > 0)
					Toast.makeText(PageAdminActivity.this, getString(messageFailId), Toast.LENGTH_LONG).show();

				switch (messageFailId)
				{

				// case R.string.message_fail_change_name:
				// break;
				//
				// case R.string.message_fail_update_all:
				// break;
				//
				// case R.string.message_fail_change_password:
				// break;

					case R.string.message_fail_change_name_relays:
					case R.string.message_fail_change_name_sensors:
					case R.string.message_fail_add_numbers_alarm:
					case R.string.message_fail_add_numbers_control:

						Utils.hideProgressDialog();
						break;

					case R.string.message_fail_control_relay:

						for (int indexView = 0; indexView < _LayoutListRelays.getChildCount(); indexView++)
						{
							View view = _LayoutListRelays.getChildAt(indexView);

							ProgressBar progressBar = (ProgressBar) view.findViewById(R.id.layout_one_relay_progress_bar);

							if (progressBar != null
									&& progressBar.getVisibility() == View.VISIBLE)
							{
								progressBar.setVisibility(View.GONE);
							}

							Button buttonRename = (Button) view.findViewById(com.hethongviet.preventer.admin.R.id.layout_one_relay_button_rename);

							buttonRename.setClickable(true);
							buttonRename.setTextColor(Color.BLACK);
						}

						break;

					case R.string.message_fail_update_relays:
						for (int indexView = 0; indexView < _LayoutListRelays.getChildCount(); indexView++)
						{
							View view = _LayoutListRelays.getChildAt(indexView);
							Button buttonRename = (Button) view.findViewById(com.hethongviet.preventer.admin.R.id.layout_one_relay_button_rename);

							buttonRename.setClickable(true);
							buttonRename.setTextColor(Color.BLACK);
						}
						_ProgressBarUpdateAllRelays.setVisibility(View.GONE);
						_ButtonUpdateAllRelays.setClickable(true);
						_ButtonUpdateAllRelays.setTextColor(Color.BLACK);

						break;

					case R.string.message_fail_update_sensors:
						for (int indexView = 0; indexView < _LayoutListSensors.getChildCount(); indexView++)
						{
							View view = _LayoutListSensors.getChildAt(indexView);
							Button buttonRename = (Button) view.findViewById(com.hethongviet.preventer.admin.R.id.layout_one_sensor_button_rename);

							buttonRename.setClickable(true);
							buttonRename.setTextColor(Color.BLACK);
						}

						_ProgressBarUpdateAllSensors.setVisibility(View.GONE);
						_ButtonUpdateAllSensors.setClickable(true);
						_ButtonUpdateAllSensors.setTextColor(Color.BLACK);

						break;

					case R.string.message_fail_synchronize_numbers_control:

						for (int index = 0; index < _NumbersControlList.size(); index++)
						{
							final Number number = _NumbersControlList.get(index);

							if (transaction.getRecipient().equals(number.getNumber()))
							{
								/* Update UI */
								View view = _LayoutListNumbersControl.getChildAt(index);
								if (view != null)
								{
									ProgressBar progressBar = (ProgressBar) view.findViewById(R.id.layout_one_number_progress_bar);

									if (progressBar != null
											&& progressBar.getVisibility() == View.VISIBLE)
									{
										progressBar.setVisibility(View.GONE);
									}

									Button buttonDelete = (Button) view.findViewById(R.id.layout_one_number_button_delete);
									Button buttonSynchronize = (Button) view.findViewById(R.id.layout_one_number_button_synchronize);
									if (buttonDelete != null)
									{
										buttonDelete.setClickable(true);
										buttonDelete.setTextColor(Color.BLACK);
									}
									if (buttonSynchronize != null)
									{
										buttonSynchronize.setClickable(true);
										buttonSynchronize.setTextColor(Color.BLACK);
									}

									ImageView imageViewSynchronize = (ImageView) view.findViewById(R.id.layout_one_number_image_synchronize);
									if (imageViewSynchronize != null)
									{
										imageViewSynchronize.setImageResource(R.drawable.synchronize_error);
										imageViewSynchronize.setVisibility(View.VISIBLE);
									}
								}

								number.setStatusSynchronize(Number.SYNCHRONIZE_ERROR);
								_NumberSQLite.insert(number);

								break;
							}
						}

						break;

					case R.string.message_fail_synchronize_numbers_alarm:

						for (int index = 0; index < _NumbersAlarmList.size(); index++)
						{
							final Number number = _NumbersAlarmList.get(index);

							if (transaction.getRecipient().equals(number.getNumber()))
							{
								/* Update UI */
								View view = _LayoutListNumbersAlarm.getChildAt(index);
								if (view != null)
								{
									ProgressBar progressBar = (ProgressBar) view.findViewById(R.id.layout_one_number_progress_bar);

									if (progressBar != null
											&& progressBar.getVisibility() == View.VISIBLE)
									{
										progressBar.setVisibility(View.GONE);
									}

									Button buttonDelete = (Button) view.findViewById(R.id.layout_one_number_button_delete);
									Button buttonSynchronize = (Button) view.findViewById(R.id.layout_one_number_button_synchronize);
									if (buttonDelete != null)
									{
										buttonDelete.setClickable(true);
										buttonDelete.setTextColor(Color.BLACK);
									}
									if (buttonSynchronize != null)
									{
										buttonSynchronize.setClickable(true);
										buttonSynchronize.setTextColor(Color.BLACK);
									}

									ImageView imageViewSynchronize = (ImageView) view.findViewById(R.id.layout_one_number_image_synchronize);
									if (imageViewSynchronize != null)
									{
										imageViewSynchronize.setImageResource(R.drawable.synchronize_error);
										imageViewSynchronize.setVisibility(View.VISIBLE);
									}
								}

								number.setStatusSynchronize(Number.SYNCHRONIZE_ERROR);
								_NumberSQLite.insert(number);

								break;
							}
						}

						break;

					default:
						break;
				}
			}
		});

	}

}
